<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\common\controller;

use think\Controller;
use zz\Html\HTMLMinify;

class BaseController extends Controller
{
    public $noCheckController = true; //本控制器是否检测权限

    protected $sysConfig = []; // 系统配置
    protected $projectConfig = []; // 项目配置

    public function initialize()
    {
        // 读取数据库里面的全局设置
        $this->getSiteConfig();
//        $this->assign('baseProjectList', $this->getBaseProjectList());
        $this->assign('baseProjectName', $this->getProjectName());
    }

    /**
     * 处理参数和搜索条件
     * @param array $whereKeys 格式
     * [
     *      [ 'key'=> 'name' , 'text'=> 'name'  , 'field' => '数据库对应的列，默认和 key一样' , 'op' => '操作符' , 'fields' => '用来指定多个列的'
     *          , 'valueMethod' => '值处理方法，比如时间等需要处理的' , 'default' => '默认值' ]
     * ]
     * @param array $search
     * @return array
     */
    public function getParamWhere($whereKeys,$search = []){
        if(empty($search)){
            $param = input('param.');
            if(empty($param['search'])){
                $search = [];
            }
            else{
                $search = $param['search'];
            }
        }

        $where = [];
        foreach ($whereKeys as $whereKey){
            //  存在 这个 参数 并且不为空字符
            if(array_key_exists($whereKey['key'],$search) && strlen($search[$whereKey['key']]) > 0){
                $field = empty($whereKey['field']) ? $whereKey['key'] : $whereKey['field'];
                //判断是否要指定列
                if(!empty($whereKey['fields'])) $field = $whereKey['fields'];

                $whereValue = $search[$whereKey['key']];
                // 值处理方法
                if(!empty($whereKey['valueMethod'])){
                    $whereValue = call_user_func_array($whereKey['valueMethod'],[$whereValue]);
                }

                // 处理 like 后续有其他的条件不符合的继续添加
                switch (strtolower($whereKey['op'])){
                    case 'ignore':  // 忽略，不进行数据库查询

                        break;
                    case ',like,':
                        $where[] = [$field,'LIKE','%,'.$whereValue.',%'];
                        break;
                    case 'like':
                        $where[] = [$field,'LIKE','%'.$whereValue.'%'];
                        break;
                    default:
                        $where[] = [$field,$whereKey['op'],$whereValue];
                        break;
                }
            }
            else{
                // 没有值 给默认值或者 给空值
                $search[$whereKey['key']] = empty($whereKey['default']) ? '' : $whereKey['default'];
            }
        }

        return [
            'where' => $where,
            'search' => $search,
        ];
    }

    /**
     * 获取分页信息
     * @param $totalRows
     * @param $pageIndex
     * @param array $search
     * @param int $pageSize
     * @param string $actionName
     * @return array
     */
    public function getPagerInfo($totalRows,$pageIndex,$search = [],$pageSize = 50,$actionName = 'index'){
        $offset = ($pageIndex - 1) * $pageSize;

        $totalPages = ceil($totalRows / $pageSize);
        $pageUrl = url($actionName) . '?t=' . time();
        // 兼容 search 外的参数
        $gets = input('param.');
        $getcanshu = [];
        foreach ($gets as $key => $val) {
            // search开头的话 跳过
            if(stripos($key,'search') === 0){
                continue;
            }
            $getcanshu[$key] = $val;
        }
        if(!empty($getcanshu)){
            $pageUrl .= '&' . http_build_query($getcanshu);
        }
        if(!empty($search)){
            $canshu = [];
            foreach ($search as $key => $item){
                $canshu['search['.$key.']'] = $item;
            }
            $pageUrl .= '&' . http_build_query($canshu);
        }
        return [
            'offset' => $offset,
            'pageIndex' => $pageIndex,
            'pageSize' => $pageSize,
            'totalPages' => $totalPages,
            'totalRows' => $totalRows,
            'pageUrl' => $pageUrl,
        ];
    }

    /**
     * 加载模板输出
     * @access protected
     * @param  string $template 模板文件名
     * @param  array  $vars     模板输出变量
     * @param  array  $config   模板参数
     * @return mixed
     */
    protected function fetch($template = '', $vars = [], $config = [])
    {
        $content = parent::fetch($template,$vars,$config);
        if(true === config('site.html_minify')){
            $content = HTMLMinify::minify($content,
                array(
                    'doctype' => HTMLMinify::DOCTYPE_HTML5,
                    'optimizationLevel' => HTMLMinify::OPTIMIZATION_ADVANCED,
//                    'emptyElementAddSlash' => true,
//                    'emptyElementAddWhitespaceBeforeSlash' => true,
                )
            );
        }
        return $content;
    }

    /**
     * 读取数据库里面的全局设置 ， 写入设置
     */
    private function getSiteConfigAllList(){
        $bLogic = new \app\common\logic\BaseLogic();
        $this->projectConfig = $bLogic->_getSiteConfigAllList($this->getProjectId());
    }

    /**
     * 选择 小区（项目）ID
     * @param $projectId
     */
    public function setProjectId($projectId){
        $baseProjectList = $this->getBaseProjectList();
        foreach ($baseProjectList as $item) {
            if($item['id'] == $projectId){
                setProjectId($item['id']);
                $this->setProjectName($item['name']);

                return true;
            }
        }
        return false;
    }

    /**
     * 选择 小区（项目）ID
     * @return mixed
     */
    public function getProjectId(){
        return getProjectId();
    }
    private function setProjectName($projectName){
        session('projectName',$projectName);
    }
    public function getProjectName(){
        return session('projectName');
    }
    public function getBaseProjectList(){
        $cacheKey = 'BaseController_getBaseProjectList';
        $baseProjectList = cache($cacheKey);
        if(empty($baseProjectList)){
            $sysLogic = new \app\common\logic\SysLogic();
            $baseProjectList = $sysLogic->_getProjectListByWhere([],'id,name');
            if (!empty($baseProjectList)) {
                cache($cacheKey, $baseProjectList,null,'system');
            }
        }

        return $baseProjectList;
    }

    public function getSiteConfig(){
        $sysLogic = new \app\common\logic\SysLogic();
        $this->projectConfig = $sysLogic->_getSiteConfigAllList($this->getProjectId());
        $this->sysConfig = $sysLogic->_getSysConfig();
    }
}